<template>
	<view class="pay" :style="css.page+'min-height:'+$xyfun.xysys().windowHeight+'px'" v-if="!isLoading">
		<view class="p-lr-30 p-tb-15 tc-r bc-w m-b-2 ts-26 tc" :style="css.tcp">
			提示：退订需在订单预定日期{{common.appConfig.returnhour}}小时前,当天场地不能退订。</view>
		<view class="item-list p-lr-30 br-10 bc-w">
			<view v-for="(g,index) in orderDetail.item" :key="index" :style="css.blpc"
				:class="'item p-tb-30 flex '+(index == orderDetail.item.length-1?'':'bl-b')">
				<view class="l ovh br-10">
					<image :src="orderDetail.storelogo" mode="widthFix" />
				</view>
				<view class="r psr m-l-20">
					<view class="tb lh-40 goods-title">
						{{orderDetail.storename}}
					</view>
					<view class="venue m-t-10">
						{{orderDetail.venuename}} - {{g.area}}
					</view>
					<view class="date m-t-20 ts-26" :style="css.tcl">
						{{g.date}} {{g.week}} {{g.starttime}}-{{g.endtime}}
					</view>
					<view class="price-box flex psa lh-32">
						<text :style="css.tcp">￥</text>
						<text :style="css.tcp" class="ts-32 tb">{{ g.price }}</text>
					</view>
				</view>
			</view>
		</view>

		<view class="coupon flex p-30 m-b-2 lh-50 bc-w m-tb-20">
			<view class="l">优惠券：</view>
			<view class="m-l-auto" @tap="showCoupon()" :style="css.tcp">抵扣¥{{orderDetail.coupon_fee}}元 <text
					class="xyicon icon-right"></text></view>
		</view>

		<view class="pay-list">
			<view class="item flex p-30 m-b-2 lh-50 bc-w" v-for="(item, index) in payList" :key="index"
				v-if="item.state">
				<view class="l flex">
					<text :class="'xyicon icon-'+item.icon+' ts-40 m-r-15 lh-40 p-t-5'"></text>
					<text class="lh-50">{{item.name}}</text>
				</view>
				<view class="r tb m-l-auto" @tap="payMethodSelect(index)">
					<text class="xyicon icon-radio-a ts-32 lh-50" v-if="item.select"></text>
					<text class="xyicon icon-radio ts-32 lh-50" v-else></text>
				</view>
			</view>
		</view>

		<view class="bottom-fixed flex tc bc-w">
			<view class="p-lr-30 p-tb-15 flex tc wa">
				<view class="lh-42 p-t-15 m-r-30"><text>需支付：</text><text class="ts-26" :style="css.tcp">¥</text><text
						class="ts-36" :style="css.tcp">{{ orderDetail.total_fee || "0.00" }}</text></view>
				<view class="action flex m-l-auto">
					<view class="sub-order m-l-auto tc-w" :style="css.mcbg" @tap="subPay()">
						确认支付
					</view>
				</view>
			</view>
		</view>

		<!--优惠券弹窗-->
		<block v-if="couponModelShow">
			<view class="xy-modal-box bottom-fixed xy-modal-box-bottom coupon-model-box ovh" :style="css.pbg"
				:class="[couponModelShow?'xy-modal-show':'']">
				<view class="title p-tb-50 tb tc" :style="css.mbg">可用优惠券</view>

				<view class="coupon-list" v-if="couponList.length > 0">
					<view class="item br-10 m-lr-30 m-b-30 p-t bc-w flex ovh" v-for="item in couponList" :key="item.id">
						<view class="l tc tc-w p-30" :style="css.mcbg">
							<view v-if="item.type == 'reward'">
								¥<text class="tb ts-46">{{$xyfun.pe(item.money)}}</text>
							</view>
							<view v-else>
								<text class="tb ts-46">{{$xyfun.pe(item.discount)}}</text>折
							</view>
							<view class="ts-26 m-t-15">
								<text v-if="item.atleast > 0">满{{$xyfun.pe(item.atleast)}}元可用</text>
								<text v-else>无限制</text>
							</view>
						</view>
						<view class="r p-30 psr">
							<view class="tb">{{item.name}}</view>
							<view v-if="item.remark" class="remark-box ts-22 fw-bold br-10 m-t-10">
								{{ item.remark }}
							</view>
							<view class="ts-24 m-t-5">
								有效期:{{ $xyfun.timeFormat(item.endtime)}}
							</view>
							<view v-if="orderDetail.user_coupon_id == item.id" class="btn ts-26 br-20 p-lr-25"
								:style="css.pbg+css.tcl">已使用</view>
							<view v-else class="btn tc-w ts-26 br-20 p-lr-25" :style="css.mcbg"
								@tap="useCoupon(item.id)">使用</view>
						</view>
					</view>
				</view>
				<view class="tc m-40 p-40" :style="css.tcl" v-else>无可用优惠券</view>

				<view class="close ts-40" :style="css.tcl" @tap="couponModelShow = false"><text
						class="xyicon icon-close"></text></view>
			</view>
			<view class="xy-modal-mask" :class="[couponModelShow?'xy-mask-show':'']"
				@tap="couponModelShow =!couponModelShow"></view>
		</block>

	</view>
</template>

<script>
	import {
		mapState
	} from 'vuex';
	import Pay from '@/utils/pay';
	import xyStoreRow from '@/components/xy-store/row';
	export default {
		components: {
			xyStoreRow,
		},
		data() {
			return {
				css: {},
				disabled: false,
				isLoading: true,
				store_id: 0,
				orderDetail: null,
				couponList: [],
				couponModelShow: false,
				payList: [{
						name: '余额支付',
						method: 'balance',
						icon: 'balance',
						state: true,
						select: true
					},
					{
						name: '微信支付',
						method: 'wechat',
						icon: 'wechat',
						state: true,
						select: false
					}
				]
			}
		},
		computed: {
			...mapState(['common', 'user'])
		},
		onLoad() {
			this.$xyfun.setNavBg();
			this.css = this.$xyfun.css();

			this.$xyfun.storeId().then((store_id) => {
				this.store_id = store_id;
				this.loadData();
			})


		},
		methods: {

			loadData() {
				this.$api.post({
					url: '/order/init',
					loadingTip: '加载中...',
					data: {
						order_id: this.$Route.query.order_id,
					},
					success: res => {
						this.isLoading = false;
						this.orderDetail = res;
						// console.log()
					},
					fail: res => {
						setTimeout(() => {
							uni.navigateBack();
						}, 2000)
					}
				});
			},

			//使用优惠券
			useCoupon(user_coupon_id) {
				const coupon = this.couponList.find(c => c.id === user_coupon_id);

				if (!coupon) {
					uni.showToast({
						title: '未找到该优惠券',
						icon: 'none'
					});
					return;
				}

				if (coupon.limit_type === 1) {
					// 判断 orderDetail.item 中是否有任意一个价格等于优惠券金额
					const hasMatch = this.orderDetail.item.some(g => Number(g.price) === Number(coupon.money));

					if (!hasMatch) {
						uni.showToast({
							title: `该优惠券只能用于${coupon.money}元场`,
							icon: 'none'
						});
						return;
					}
				}

				this.$api.post({
					url: '/order/useCoupon',
					data: {
						order_id: this.orderDetail.id,
						user_coupon_id: user_coupon_id
					},
					success: res => {
						console.log(res);
						this.couponModelShow = false;
						this.loadData();
					}
				});
			},

			//用户可用优惠券
			showCoupon() {
				this.$api.post({
					url: '/user_coupon/lists',
					loadingTip: '加载中...',
					data: {
						store_id: this.store_id,
						atleast: this.orderDetail.total_amount,
						status: 0
					},
					success: res => {
						this.couponModelShow = true;
						this.couponList = res.data;
					}

				});
			},

			// 支付方式选择
			payMethodSelect(key) {
				const item = this.payList[key]

				// 判断：金额为 0 且选择微信支付
				if (Number(this.orderDetail.total_fee) <= 0 && item.method === 'wechat') {
					uni.showToast({
						title: '金额为 0 元不可使用微信支付',
						icon: 'none'
					})
					return
				}

				// 切换选中状态
				this.payList.map((value, index) => {
					value.select = (index === key) ? !value.select : false
				})
			},

			//确认支付
			subPay() {

				if (this.orderDetail != null && !this.disabled) {
					var pay_type = '';
					this.payList.map((value) => {
						if (value.select) {
							pay_type = value.method;
						}
					});
					// 判断：金额为 0 且选择微信支付
					if (Number(this.orderDetail.total_fee) <= 0 && pay_type === 'wechat') {
						this.$xyfun.msg('金额为 0 元，只能使用余额支付');

						// 自动切换为余额支付
						this.payList.forEach(item => {
							item.select = (item.method === 'balance');
						});
						pay_type = 'balance';
						return;
					}
					if (!pay_type) {
						this.$xyfun.msg('请选择支付方式');
					} else {
						// 支付订单
						if (pay_type == 'wechat') {
							console.log(this.orderDetail)
							this.$xyfun.storeId().then((store_id) => {
								this.$api.post({
									url: '/Shande/test',
									data: {
										orderjson: this.orderDetail
									},
									success: res => {
										const jsonData = JSON.parse(res.data);
										const payDataString = jsonData
											.pay_data; // 获取 pay_data 的 JSON 字符串
										const payData = JSON.parse(payDataString); // 解析成对象
										return new Promise((resolve, reject) => {
											uni.requestPayment({
												appId: payData.appId,
												nonceStr: payData.nonceStr,
												package: payData.package,
												paySign: payData.paySign,
												signType: payData.signType,
												timeStamp: payData.timeStamp,
												success: (e) => {
													uni.showModal({
														content: "预约成功",
														showCancel: false,
														success: (res) => {
															// console.log("res.confirm:" + res.confirm);
															if (res
																.confirm
															) {
																uni.switchTab({
																	url: '/pages/index' // 这里使用 switchTab 进行跳转
																});
															}
														}
													});
												},
												fail: (e) => {
													uni.showModal({
														content: "支付失败,原因为: " +
															e.errMsg,
														showCancel: false
													})
												}
											})
										});
									}
								});
							})
						} else {
							this.$xyfun.storeId().then((store_id) => {
								this.$api.post({
									url: '/pay/prepay',
									data: {
										order_sn: this.orderDetail.order_sn,
										payment: 'balance',
										order_type: 'order',
										user_id: uni.getStorageSync('xyvenue:user').id,
										store_id: store_id,
										amount: this.orderDetail.total_fee
									},
									success: res => {
										uni.navigateTo({
											url: `/pages/user/order/payresult?orderId=${this.orderDetail.id}&type=balance&payment=balance&payState=success&orderType=order`
										})
									},
									fail: res => {
										console.log(res);
										this.disabled = false;
									}
								});
							})
						}
					}
				}
			}


		}
	}
</script>

<style scoped lang="scss">
	.line {
		height: 4rpx;
		width: 34%;
		margin: 0 auto;
	}

	.item-list {
		.item {
			.l {
				width: 150rpx;
				height: 150rpx;

				image {
					width: 150rpx;
					height: 150rpx;
				}
			}

			.r {
				width: 510rpx;

				.price-box {
					position: absolute;
					right: 0;
					top: 0;
				}
			}
		}
	}

	.bottom-fixed {
		.sub-order {
			width: 260rpx;
			height: 74rpx;
			border-radius: 37rpx;
			line-height: 74rpx;
		}
	}

	.coupon-model-box {
		height: 900rpx;
		border-radius: 30rpx 30rpx 0 0;

		.ewm image {
			width: 300rpx;
			height: 300rpx;
		}

		.coupon-list {
			height: 700rpx;
			overflow-y: scroll;
		}

		.close {
			position: absolute;
			right: 30rpx;
			top: 30rpx;
		}

		.coupon-list {
			.item {
				.l {
					width: 180rpx;
				}

				.r {
					width: 390rpx;

					.btn {
						position: absolute;
						right: 30rpx;
						top: 30rpx;
					}
				}
			}
		}

	}

	.pay-model-box {
		width: 80%;
	}

	/* 可放在 page 样式或 global.scss 中 */
	.remark-box {
		// background-color: #ff4d4f;
		/* 鲜艳红色（也可用 #f56c6c） */
		color: #ff4d4f;
		// border-left: 6rpx solid #fff176;
		/* 增加左侧亮色条做点缀 */
	}
</style>